package com.sky.asp;


import com.sky.annotion.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.constant.JwtClaimsConstant;
import com.sky.enumeration.MapperMethodEnum;
import com.sky.properties.JwtProperties;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;


@Aspect
@Component
public class AutoFillAOP {
    @Autowired
    JwtProperties jwtProperties;
    @Autowired
    HttpServletRequest httpServletRequest;

    @Pointcut("execution(* com.sky.mapper.*.* (..)) && @annotation(com.sky.annotion.AutoFill)")
    public void pointcut() {
    }

    @Before("pointcut()")
    public void autoFill(JoinPoint joinPoint) {
        //获取登入者的id
        String token = httpServletRequest.getHeader(jwtProperties.getAdminTokenName());
        Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
        Long id = Long.valueOf(claims.get(JwtClaimsConstant.EMP_ID).toString());
        //获取方法形参
        Object[] args = joinPoint.getArgs();
        //断言 方法形参必为一个
        if (args.length == 1) {
            //要注入的形参对象
            Object object = args[0];
            //开始反射
            Class<?> aClass = object.getClass();
            //获取拦截到方法上的注解
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            AutoFill annotation = signature.getMethod().getAnnotation(AutoFill.class);
            try {
                if (annotation.value() == MapperMethodEnum.INSERT) { //执行新增操作
                    //使用映射完成赋值
                    aClass.getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class).invoke(object, LocalDateTime.now());
                    aClass.getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class).invoke(object, id);
                }
                //使用映射完成赋值
                aClass.getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class).invoke(object, LocalDateTime.now());
                aClass.getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class).invoke(object, id);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
}
